package com.gingko.duominuo.ui.activity

import android.app.Activity
import android.os.Bundle
import android.view.MotionEvent
import android.view.View
import android.view.inputmethod.InputMethodManager
import androidx.appcompat.app.AppCompatActivity
import androidx.core.content.ContextCompat
import androidx.lifecycle.observe
import com.gingko.duominuo.R
import com.gingko.duominuo.ui.widget.LoadDialog
import com.gingko.duominuo.utils.*
import com.gingko.duominuo.viewmodel.BaseViewModel

abstract class BaseActivity : AppCompatActivity() {
    private val loadDialog by lazy {
        LoadDialog.also {
            it.isCancelable = false
        }
    }

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(getContentView())
        pushActivity(this)
        StatusBarUtil.setTranslucent(this, 0)
        StatusBarUtil.setLightMode(this)
        getViewModel()?.loadingLiveData?.observe(owner = this) {
            "activity--isShowLoading:$it".logi("------------>")
            if (it) {
                showLoading()
            } else {
                dismissLoading()
            }
        }
        initView(savedInstanceState)
    }

    abstract fun getContentView(): View

    abstract fun getViewModel(): BaseViewModel?

    abstract fun initView(savedInstanceState: Bundle?)


    fun showLoading(message: String = getString(R.string.data_loading)) {
        loadDialog.show(supportFragmentManager, "LoadingDialog", message)
    }


    fun dismissLoading() {
        loadDialog.dismiss()
    }

    /**
     * 点击空白处隐藏软键盘
     */
    override fun dispatchTouchEvent(ev: MotionEvent): Boolean {
        if (ev.action == MotionEvent.ACTION_DOWN && null != currentFocus) {
            val imm = getSystemService(Activity.INPUT_METHOD_SERVICE) as InputMethodManager
            imm.hideSoftInputFromWindow(currentFocus?.windowToken, 0)
        }
        return super.dispatchTouchEvent(ev)
    }

    override fun onDestroy() {
        super.onDestroy()
        hideSoftInput(this)
        popActivity(this)
    }

}